<template>
  <div>
    <label v-if="label">{{label}}</label>

    <!-- input占位符 -->
    <slot></slot>
    
    <p v-if="error" class="error">{{error}}</p>
  </div>
</template>

<script>
import schema from 'async-validator';
export default {
  components:{},
  inject:['form'],//注入父组件传递下来的实例
  props:{
    label:{
      type:String
    },
    prop:{
      type:String
    }
  },
  data(){
    return {
      error: '',//属于组件自身特性
    }
  },
  watch:{},
  computed:{},
  methods:{
    //执行具体校验
    validate:function(key){
      // 1.获取校验规则
      // 2.获取数据模型
      // console.log("form跨代传递的校验规则：",this.form.rules[this.prop])
      // console.log("form跨代传递的数据模型：",this.form.model[this.prop])

      let theItem = this.prop;
      let theRules = this.form.rules[theItem];
      let theValue = this.form.model[theItem];
      const descriptor = { [theItem]:theRules };

      // 创建校验器
      let validator = new schema(descriptor);
      return validator.validate({ [theItem]:theValue},(errors, fileds)=>{
        if(errors){
          this.handleErrors(errors, fileds);
        }else{
          // validation passed
          this.error = '';
          return null;
        }
      })
      // .then(() => {
      //   // validation passed
      //   this.error = '';
      // })
      // .catch(({ errors, fields }) => {
      //   return this.handleErrors(errors, fields);
      // })
    },

    handleErrors:function(errors, fileds){
      this.error = errors[0].message;
      // console.log("errors:",errors)
      // this.$parent.$emit("validate_failed",{data:errors})
    }
  },
  created(){},
  mounted(){
    //监听校验通知
    this.$on("validate",this.validate)
  },
  destroyed(){}
}
</script>
<style lang="scss" scoped>
  .error{
    background: lightcoral;
    color: white;
  }
</style>